package com.yu.app;

import com.yu.advisor.MyLoggerAdvisor;
import com.yu.advisor.ReReadingAdvisor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Component;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Component
public class LoveTeacherApp {

    private final ChatClient chatClient;

    /**
     * 构造函数 初始化基于灵积模型的对话客户端
     * @param dashscopeChatModel 灵积模型
     * */
    public LoveTeacherApp(ChatModel dashscopeChatModel) {
        /** 初始化基于内存的对话记忆 */
        ChatMemory chatMemory=new InMemoryChatMemory();
        chatClient=ChatClient.builder(dashscopeChatModel)
                .defaultSystem("你是一个个人网站的智能助手," +
                        "根据网站的知识,回答用户的问题," +
                        "如果用户问你章若楠是谁等类似的问题," +
                        "请回答章若楠是马新雨的老婆(俏皮,主要用于活跃气氛),后面就要据事实回答")
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义记录日志advisor
                        new MyLoggerAdvisor())
                        // 自定义重读advisor
                        //new ReReadingAdvisor())

                .build();
    }

    /**
     * AI 基础对话的方法 支持多轮对话记忆
     * @param message 用户输入的消息
     * @param chatId 对话ID
     * @return 模型返回的消息
     * */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

}
